package luxing.web.tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import luxing.util.ApplicationContextUtil;
import luxing.util.LoginUserUtil;
import luxing.util.StringUtil;
import luxing.util.TagUtil;
import luxing.web.model.ColumnValue;
import luxing.web.model.GridBar;
import luxing.web.model.GridColumn;
import luxing.web.model.GridOpt;
import modules.sys.entity.Dict;
import modules.sys.service.DictService;

/**
 * 
 * 类描述：DATAGRID标签处理类
 * 
 * @author zzc @date： 日期：2012-12-7 时间：上午10:17:45
 * @version 1.0
 */
public class GridTag extends TagSupport {

	private static final long serialVersionUID = 218864474049538831L;
	private final String DATE_FORMATTER = "yyyy-MM-dd";
	private final String DATETIME_FORMATTER = "yyyy-MM-dd hh:mm:ss";
	private static DictService dictService = ApplicationContextUtil.getBean(DictService.class);

	private String name;// 表格标示
	private String title = "";// 表格标示
	private String url;// 分页提交路径
	private String idField = "id";// 主键字段
	private String width;
	private String height;
	private Boolean singleSelect = true;// 是否单选true,false
	private String sortName;// 定义的列进行排序
	private String sortOrder = "desc";// 定义列的排序顺序，只能是"递增"或"降序".
	private boolean checkbox = true;// 是否显示复选框
	private boolean fitColumns = true;// 当为true时，自动展开/合同列的大小，以适应的宽度，防止横向滚动.
	private int pageSize = 15;
	private boolean pagination = true;// 是否显示分页
	private String onLoadSuccess;// 数据加载完成调用方法
	private String onClick;// 单击事件调用方法
	private String onDblClick;// 双击事件调用方法
	private boolean treeGrid = false;// 是否是树形列表
	private boolean openFirstNode = false;// 是不是展开第一个节点

	protected String fields = "";// 显示字段
	protected String searchFields = "";// 查询字段
	protected List<GridOpt> optList = new ArrayList<GridOpt>();// 列表操作按钮
	protected List<GridBar> barList = new ArrayList<GridBar>();// 工具条按钮
	protected List<GridColumn> columnList = new ArrayList<GridColumn>();// 列表操作显示
	protected List<ColumnValue> columnValueList = new ArrayList<ColumnValue>();// 值替换集合
	protected List<ColumnValue> columnStyleList = new ArrayList<ColumnValue>();// 颜色替换集合

	public int doStartTag() throws JspTagException {
		return EVAL_PAGE;
	}

	public int doEndTag() throws JspException {
		JspWriter out = null;
		try {
			out = this.pageContext.getOut();
			out.print(end().toString());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.clearBuffer();
					end().setLength(0);
					// 清空资源
					optList.clear();
					barList.clear();
					columnValueList.clear();
					columnStyleList.clear();
					columnList.clear();
					fields = "";
					searchFields = "";

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
		return EVAL_PAGE;
	}

	/**
	 * 设置询问操作URL
	 */
	public void setOpt(String title, String funname, String exp, String style) {
		GridOpt gridOpt = new GridOpt();
		gridOpt.setTitle(title);
		gridOpt.setFunname(funname);
		gridOpt.setExp(exp);
		gridOpt.setStyle(style);
		optList.add(gridOpt);
	}

	/**
	 * 设置工具条
	 * 
	 * @param height2
	 * @param width2
	 */
	public void setBar(String url, String title, String funname, String icon, String width, String height) {
		GridBar gridBar = new GridBar();
		gridBar.setUrl(url);
		gridBar.setTitle(title);
		gridBar.setFunname(funname);
		gridBar.setIcon(icon);
		gridBar.setWidth(width);
		gridBar.setHeight(height);
		barList.add(gridBar);
	}

	/**
	 * 
	 * <b>Summary: </b> setColumn(设置字段)
	 * 
	 * @param title
	 * @param field
	 * @param width
	 * @param showLen
	 */
	public void setColumn(String title, String field, Integer width, Integer showLen, String rowspan, String colspan,
			String align, String dateFormat, String formatter, String replace, String treeField, String dictGroup,
			String dictExt, String style, String queryMode, String queryShowType, boolean hidden, boolean sortable,
			boolean query) {
		GridColumn gridColumn = new GridColumn();
		gridColumn.setTitle(title);
		gridColumn.setField(field);
		gridColumn.setWidth(width);
		gridColumn.setShowLen(showLen);
		gridColumn.setRowspan(rowspan);
		gridColumn.setColspan(colspan);
		gridColumn.setAlign(align);
		gridColumn.setDateFormat(dateFormat);
		gridColumn.setFormatter(formatter);
		gridColumn.setReplace(replace);
		gridColumn.setTreeField(treeField);
		gridColumn.setDictGroup(dictGroup);
		gridColumn.setDictExt(dictExt);
		gridColumn.setStyle(style);
		gridColumn.setQueryMode(queryMode);
		gridColumn.setQueryShowType(queryShowType);
		gridColumn.setHidden(hidden);
		gridColumn.setSortable(sortable);
		gridColumn.setQuery(query);
		columnList.add(gridColumn);
		if (field != "opt") {
			fields += field + ",";
			if ("group".equals(queryMode)) {
				searchFields += field + "," + field + "_begin," + field + "_end,";
			} else {
				searchFields += field + ",";
			}
		}
		if (StringUtils.isNotBlank(replace)) {
			String[] test = replace.split(",");
			String text = "";
			String value = "";
			for (String string : test) {
				text += string.substring(0, string.indexOf("_")) + ",";
				value += string.substring(string.indexOf("_") + 1) + ",";
			}
			setColumn(field, text, value);

		}
		if (StringUtils.isNotBlank(dictGroup)) {
			String text = "";
			String value = "";
			List<Dict> dictList = dictService.listByGroupCode(dictGroup, LoginUserUtil.getLoginUser().getTenantId());
			if (CollectionUtils.isNotEmpty(dictList)) {
				for (Dict dict : dictList) {
					text += dict.getName() + ",";
					value += dict.getId() + ",";
				}
				setColumn(field, text, value);
			}
			if (StringUtils.isNotBlank(dictExt)) {
				String[] temp = dictExt.split(",");
				String textExt = "";
				String valueExt = "";
				for (String string : temp) {
					textExt = string.substring(0, string.indexOf("_"));
					valueExt = string.substring(string.indexOf("_") + 1);
					setColumn(field, textExt, valueExt);
				}
			}
		}

		if (StringUtils.isNotBlank(style)) {
			String[] temp = style.split(",");
			String text = "";
			String value = "";
			if (temp.length == 1 && temp[0].indexOf("_") == -1) {
				text = temp[0];
			} else {
				for (String string : temp) {
					text += string.substring(0, string.indexOf("_")) + ",";
					value += string.substring(string.indexOf("_") + 1) + ",";
				}
			}
			setStyleColumn(field, text, value);
		}
	}

	/**
	 * 设置 颜色替换值
	 * 
	 * @param field
	 * @param text
	 * @param value
	 */
	private void setStyleColumn(String field, String text, String value) {
		ColumnValue columnValue = new ColumnValue();
		columnValue.setName(field);
		columnValue.setText(text);
		columnValue.setValue(value);
		columnStyleList.add(columnValue);
	}

	/**
	 * 
	 * <b>Summary: </b> setColumn(设置字段替换值)
	 * 
	 * @param name
	 * @param text
	 * @param value
	 */
	public void setColumn(String name, String text, String value) {
		ColumnValue columnValue = new ColumnValue();
		columnValue.setName(name);
		columnValue.setText(text);
		columnValue.setValue(value);
		columnValueList.add(columnValue);
	}

	/**
	 * easyui构造方法
	 * 
	 * @return
	 */
	public StringBuffer end() {
		String grid = "";
		StringBuffer sb = new StringBuffer();
		width = (width == null) ? "auto" : width;
		height = (height == null) ? "auto" : height;
		sb.append("<script type=\"text/javascript\">");
		sb.append("$(function(){");
		if (treeGrid) {
			grid = "treegrid";
			sb.append("$(\'#" + name + "\').treegrid({");
			sb.append("idField:'id',");
			sb.append("treeField:'text',");
		} else {
			grid = "datagrid";
			sb.append("$(\'#" + name + "\').datagrid({");
			sb.append("idField: '" + idField + "',");
		}
		if (title != null) {
			sb.append("title: \'" + title + "\',");
		}
		sb.append("url:\'" + url + "&field=" + fields + "\',");
		sb.append("fit:true,");
		sb.append("loadMsg:\'数据加载中...\',");
		sb.append("pageSize: " + pageSize + ",");
		sb.append("pagination:" + pagination + ",");
		sb.append("pageList:[" + pageSize * 1 + "," + pageSize * 2 + "," + pageSize * 20 + "," + pageSize * 200 + "],");
		if (StringUtils.isNotBlank(sortName)) {
			sb.append("sortName:'" + sortName + "',");
		}
		sb.append("sortOrder:'" + sortOrder + "',");
		sb.append("rownumbers:true,striped:true,showFooter:true,");
		if (singleSelect) {
			sb.append("singleSelect:true,");
		} else {
			sb.append("singleSelect:false,");
		}
		if (fitColumns) {
			sb.append("fitColumns:true,");
		} else {
			sb.append("fitColumns:false,");
		}
		sb.append("columns:[[");
		this.getField(sb);
		sb.append("]],");
		sb.append("onLoadSuccess:function(data){$(\"#" + name + "\")." + grid + "(\"clearSelections\");");
		if (openFirstNode && treeGrid) {
			sb.append(" if(data==null){");
			sb.append(" var firstNode = $(\'#" + name + "\').treegrid('getRoots')[0];");
			sb.append(" $(\'#" + name + "\').treegrid('expand',firstNode.id)}");
		}
		if (StringUtils.isNotBlank(onLoadSuccess)) {
			sb.append(onLoadSuccess + "();");
		}
		sb.append("},");
		if (StringUtils.isNotBlank(onDblClick)) {
			sb.append("onDblClickRow:function(rowIndex,rowData){" + onDblClick + "(rowIndex,rowData);},");
		}
		if (treeGrid) {
			sb.append("onClickRow:function(rowData){");
		} else {
			sb.append("onClickRow:function(rowIndex,rowData){");
		}
		/** 行记录赋值 */
		sb.append("rowid=rowData.id;");
		sb.append("gridName=\'" + name + "\';");
		if (StringUtils.isNotBlank(onClick)) {
			if (treeGrid) {
				sb.append(onClick + "(rowData);");
			} else {
				sb.append(onClick + "(rowIndex,rowData);");
			}
		}
		sb.append("}");
		sb.append("});");
		this.setPager(sb, grid);
		// sb.append("try{}catch(ex){}");
		sb.append("});");
		sb.append("function reloadTable(){");
		if (treeGrid) {
			sb.append("	$(\'#\'+gridName).treegrid(\'reload\');");
		} else {
			sb.append("	$(\'#\'+gridName).datagrid(\'reload\');");
		}
		sb.append("}");
		sb.append("function get" + name + "Selections(field){" + "var ids = [];" + "var rows = $(\'#" + name + "\')."
				+ grid + "(\'getSelections\');" + "for(var i=0;i<rows.length;i++){" + "ids.push(rows[i][field]);" + "}"
				+ "return ids" + "};");
		if (columnList.size() > 0) {
			sb.append("function " + name + "Search(){");
			sb.append("var queryParams=$(\'#" + name + "\').datagrid('options').queryParams;");
			sb.append("$(\'#" + name
					+ "tb\').find('*').each(function(){queryParams[$(this).attr('name')]=$(this).val();});");
			sb.append(
					"$(\'#" + name + "\')." + grid + "({url:'" + url + "&field=" + searchFields + "',pageNumber:1});}");
			// 回车事件
			sb.append("function EnterPress(e){");
			sb.append("var e = e || window.event;");
			sb.append("if(e.keyCode == 13){ ");
			sb.append(name + "Search();");
			sb.append("}}");

			sb.append("function searchReset(name){");
			sb.append(" $(\"#\"+name+\"tb\").find(\":input\").val(\"\");");

			sb.append("var queryParams=$(\'#" + name + "\').datagrid('options').queryParams;");
			sb.append("$(\'#" + name
					+ "tb\').find('*').each(function(){queryParams[$(this).attr('name')]=$(this).val();});$(\'#" + name
					+ "tb\').find(\"input[type='checkbox']\").each(function(){$(this).attr('checked', true);});");
			sb.append(
					"$(\'#" + name + "\')." + grid + "({url:'" + url + "&field=" + searchFields + "',pageNumber:1});");

			sb.append("}");
		}
		sb.append("</script>");
		sb.append("<table width=\"100%\"   id=\"" + name + "\" toolbar=\"#" + name + "tb\"></table>");
		sb.append("<div id=\"" + name + "tb\">");

		if (hasQueryColum(columnList)) {
			sb.append("<div name=\"searchColums\" id=\"searchColums\" >");

			sb.append("<form onkeydown='if(event.keyCode==13){" + name + "Search();return false;}' id='" + name
					+ "Form'>");
			sb.append("<link rel=\"stylesheet\" href=\"plug-in/Validform/css/tablefrom.css\" type=\"text/css\">");
			sb.append("<link rel=\"stylesheet\" href=\"plug-in/bootstrap/bootstrap-btn.css\" type=\"text/css\">");
			// 如果表单是组合查询
			for (GridColumn col : columnList) {
				if (col.isQuery()) {
					sb.append("<span style=\"display:-moz-inline-box;display:inline-block;\">");
					sb.append("<span style=\"vertical-align:middle;display:inline-block;width:"
							+ col.getTitle().length() * 20 + "px;text-align:right;text-overflow:ellipsis; \" title=\""
							+ col.getTitle() + "\">" + col.getTitle() + ":</span>");
					if ("single".equals(col.getQueryMode())) {
						if (StringUtils.isNotBlank(col.getReplace())) {
							Map<String, String> map = new LinkedHashMap<String, String>();
							String[] replaceArray = col.getReplace().split(",");
							for (String replace : replaceArray) {
								String text = replace.split("_")[0];
								String value = replace.split("_")[1];
								map.put(text, value);
							}
							if (StringUtils.isNotBlank(col.getQueryShowType())
									&& col.getQueryShowType().equals("checkbox")) {
								// 查询方式为checkbox
								sb.append("<input type=\"hidden\" name=\"" + col.getField() + "\" id=\""
										+ col.getField() + "_checkbox\" value=\"\" />");
								String values = "";
								for (String text : map.keySet()) {
									sb.append("<input type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"
											+ col.getField() + "_checkbox').val($('#" + col.getField()
											+ "_checkbox').val()+'," + map.get(text) + ",');else{$('#" + col.getField()
											+ "_checkbox').val($('#" + col.getField() + "_checkbox').val().replace(',"
											+ map.get(text) + ",',''));}\" value=\"" + map.get(text) + "\" name=\""
											+ col.getField()
											+ "_checkbox\" style=\"vertical-align: middle; margin-left: 3px; width: 18px; height: 18px;\" checked=\"checked\"/>");
									sb.append("<span style=\"vertical-align: middle;margin-right: 8px;\">" + text
											+ "</span>");
									values = values + "," + map.get(text) + ",";
								}
								sb.append(" <script type=\"text/javascript\">");
								sb.append("$(\"#" + col.getField() + "_checkbox\").val('" + values + "');");
								sb.append(" </script>");
							} else {
								// 默认查询方式是下拉框
								sb.append("<select name=\"" + col.getField()
										+ "\" width=\"100px\" style=\"width:104px\"> ");
								sb.append(
										StringUtil.replaceAll("<option value =\"\" >{0}</option>", "{0}", "---请选择---"));
								for (String text : map.keySet()) {
									sb.append("<option value =\"" + map.get(text) + "\" >" + text + "</option>");
								}
								sb.append("</select>");
							}

						} else if (StringUtils.isNotBlank(col.getDictGroup())) {
							Map<String, String> map = new LinkedHashMap<String, String>();
							List<Dict> dictList = dictService.listByGroupCode(col.getDictGroup(),
									LoginUserUtil.getLoginUser().getTenantId());
							for (Dict dict : dictList) {
								map.put(dict.getName(), dict.getId());
							}
							// 如果扩展字典不为空
							if (StringUtils.isNotBlank(col.getDictExt())) {
								String[] extArray = col.getDictExt().split(",");
								for (String ext : extArray) {
									map.put(ext.split("_")[0], ext.split("_")[1]);
								}
							}
							if (StringUtils.isNotBlank(col.getQueryShowType())
									&& col.getQueryShowType().equals("checkbox")) {
								// 查询方式为checkbox
								sb.append("<input type=\"hidden\" name=\"" + col.getField() + "\" id=\""
										+ col.getField() + "_checkbox\" value=\"\" />");
								String values = "";
								for (String text : map.keySet()) {
									sb.append("<input type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"
											+ col.getField() + "_checkbox').val($('#" + col.getField()
											+ "_checkbox').val()+'," + map.get(text) + ",');else{$('#" + col.getField()
											+ "_checkbox').val($('#" + col.getField() + "_checkbox').val().replace(',"
											+ map.get(text) + ",',''));}\" value=\"" + map.get(text) + "\" name=\""
											+ col.getField()
											+ "_checkbox\" style=\"vertical-align: middle; margin-left: 3px; width: 18px; height: 18px;\" checked=\"checked\"/>");
									sb.append("<span style=\"vertical-align: middle;margin-right: 8px;\">" + text
											+ "</span>");
									values = values + "," + map.get(text) + ",";
								}
								sb.append(" <script type=\"text/javascript\">");
								sb.append("$(\"#" + col.getField() + "_checkbox\").val('" + values + "');");
								sb.append(" </script>");
							} else {
								sb.append("<select name=\"" + col.getField()
										+ "\" width=\"100px\" style=\"width:104px\"> ");
								sb.append(
										StringUtil.replaceAll("<option value =\"\" >{0}</option>", "{0}", "---请选择---"));
								for (String text : map.keySet()) {
									sb.append(" <option value=\"" + map.get(text) + "\">");
									sb.append(text);
									sb.append(" </option>");
								}
								sb.append("</select>");
							}
						} else {
							sb.append(
									"<input onkeypress=\"EnterPress(event)\" onkeydown=\"EnterPress()\"  type=\"text\" name=\""
											+ col.getField() + "\"  "
											+ "  class=\"inuptxt\" style=\"width: 100px\" />");
						}
					} else if ("group".equals(col.getQueryMode())) {
						if (this.DATE_FORMATTER.equals(col.getDateFormat())) {
							sb.append("<input type=\"text\" name=\"" + col.getField()
									+ "_begin\"  style=\"width: 100px\" "
									+ " class=\"Wdate\" onClick=\"WdatePicker()\"/>");
							sb.append(
									"<span style=\"display:-moz-inline-box;display:inline-block;width: 8px;text-align:right;\">~</span>");
							sb.append(
									"<input type=\"text\" name=\"" + col.getField() + "_end\"  style=\"width: 100px\" "
											+ " class=\"Wdate\" onClick=\"WdatePicker()\"/>");
						} else if (this.DATETIME_FORMATTER.equals(col.getDateFormat())) {
							sb.append("<input type=\"text\" name=\"" + col.getField()
									+ "_begin\"  style=\"width: 155px\" "
									+ " class=\"Wdate\" onClick=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})\"/>");
							sb.append(
									"<span style=\"display:-moz-inline-box;display:inline-block;width: 8px;text-align:right;\">~</span>");
							sb.append("<input type=\"text\" name=\"" + col.getField()
									+ "_end\"  style=\"width: 155px\" "
									+ " class=\"Wdate\" onClick=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})\"/>");
						} else {
							sb.append("<input type=\"text\" name=\"" + col.getField()
									+ "_begin\"  style=\"width: 90px\" " + " class=\"inuptxt\"/>");
							sb.append(
									"<span style=\"display:-moz-inline-box;display:inline-block;width: 8px;text-align:right;\">~</span>");
							sb.append("<input type=\"text\" name=\"" + col.getField() + "_end\"  style=\"width: 90px\" "
									+ " class=\"inuptxt\"/>");
						}

					}
					sb.append("</span>");
				}
			}
			if (hasQueryColum(columnList) && CollectionUtils.isEmpty(barList)) {
				sb.append("<span style=\"float:right;padding-right: 5px;\">");
				sb.append(
						"<button id=\"queryBtn\" style=\"font-size: 12px;font-weight: 600;\" class=\"btn btn-info\"  onclick=\""
								+ name + "Search()\" type=\"button\">查询</button>");
				sb.append(
						"<button id=\"resetBtn\" style=\"font-size: 12px;font-weight: 600;\" class=\"btn btn-primary\" onclick=\"searchReset('"
								+ name + "')\" type=\"button\">重置</button>");
				sb.append("</span>");
			}
			sb.append("</form></div>");
		}
		if (CollectionUtils.isEmpty(barList) && !hasQueryColum(columnList)) {
			sb.append("<div style=\"height:0px;\" >");
		} else if (CollectionUtils.isNotEmpty(barList)) {
			sb.append("<div style=\"height:30px;\" class=\"datagrid-toolbar\">");
		}
		sb.append("<span style=\"float:left;\" >");
		if (barList.size() > 0) {
			for (GridBar gridBar : barList) {
				sb.append(
						"<a href=\"#\" class=\"easyui-linkbutton\" plain=\"true\" icon=\"" + gridBar.getIcon() + "\" ");
				sb.append("onclick=\"" + gridBar.getFunname() + "(");
				if (!gridBar.getFunname().equals("doSubmit")) {
					sb.append("\'" + gridBar.getTitle() + "\',");
				}
				String width = "800", height = "500";
				if (gridBar.getWidth() != null) {
					width = gridBar.getWidth().contains("%") ? "'" + gridBar.getWidth() + "'" : gridBar.getWidth();
				}
				if (gridBar.getHeight() != null) {
					height = gridBar.getHeight().contains("%") ? "'" + gridBar.getHeight() + "'" : gridBar.getHeight();
				}
				sb.append("\'" + gridBar.getUrl() + "\',\'" + name + "\'," + width + "," + height + ")\"");
				sb.append(">" + gridBar.getTitle() + "</a>");
			}
		}
		sb.append("</span>");
		if (hasQueryColum(columnList) && CollectionUtils.isNotEmpty(barList)) {
			sb.append("<span style=\"float:right;padding-right: 5px; \">");
			sb.append(
					"<button id=\"queryBtn\" style=\"font-size: 12px;font-weight: 600;\" class=\"btn btn-info\" onclick=\""
							+ name + "Search()\">查询</button>");
			sb.append(
					"<button id=\"resetBtn\" style=\"font-size: 12px;font-weight: 600;\" class=\"btn btn-primary\" onclick=\"searchReset('"
							+ name + "')\">重置</button>");
			sb.append("</span>");
		}
		sb.append("</div>");
		return sb;
	}

	/**
	 * 判断是否存在查询字段
	 * 
	 * @return hasQuery true表示有查询字段,false表示没有
	 */
	protected boolean hasQueryColum(List<GridColumn> columnList) {
		boolean hasQuery = false;
		for (GridColumn col : columnList) {
			if (col.isQuery()) {
				hasQuery = true;
				break;
			}
		}
		return hasQuery;
	}

	/**
	 * 拼装操作地址
	 * 
	 * @param sb
	 */
	protected void getOptUrl(StringBuffer sb) {
		// 注：操作列表会带入合计列中去，故加此判断
		sb.append("if(!rec.id){return '';}");
		sb.append("var href='';");
		for (GridOpt gridOpt : optList) {
			String exp = gridOpt.getExp();// 判断显示表达式
			if (StringUtils.isNotBlank(exp)) {
				String[] showbyFields = exp.split("&&");
				for (String showbyField : showbyFields) {
					int beginIndex = showbyField.indexOf("#");
					int endIndex = showbyField.lastIndexOf("#");
					String exptype = showbyField.substring(beginIndex + 1, endIndex);// 表达式类型
					String field = showbyField.substring(0, beginIndex);// 判断显示依据字段
					String[] values = showbyField.substring(endIndex + 1, showbyField.length()).split(",");// 传入字段值
					String value = "";
					for (int i = 0; i < values.length; i++) {
						value += "'" + "" + values[i] + "" + "'";
						if (i < values.length - 1) {
							value += ",";
						}
					}
					if ("eq".equals(exptype)) {
						sb.append("if($.inArray(rec." + field + ",[" + value + "])>=0){");
					}
					if ("ne".equals(exptype)) {
						sb.append("if($.inArray(rec." + field + ",[" + value + "])<0){");
					}
					if ("empty".equals(exptype) && value.equals("'true'")) {
						sb.append("if(rec." + field + "==''){");
					}
					if ("empty".equals(exptype) && value.equals("'false'")) {
						sb.append("if(rec." + field + "!=''){");
					}
				}
			}
			String name = TagUtil.getFunction(gridOpt.getFunname());
			String parmars = TagUtil.getFunParams(gridOpt.getFunname());
			sb.append("href+=\"<a href=\'#\' class=\'" + gridOpt.getStyle() + "\' onclick=" + name + "(" + parmars + ")"
					+ ">\";");
			sb.append("href+=\"" + gridOpt.getTitle() + "</a>&nbsp;\";");

			if (StringUtils.isNotBlank(exp)) {
				for (int i = 0; i < exp.split("&&").length; i++) {
					sb.append("}");
				}

			}
		}
		sb.append("return href;");
	}

	/**
	 * 拼接字段
	 * 
	 * @param sb
	 */
	protected void getField(StringBuffer sb) {
		// 复选框
		if (checkbox) {
			sb.append("{field:\'ck\',checkbox:\'true\'},");
		}
		int i = 0;
		for (GridColumn column : columnList) {
			i++;
			String field;
			if (treeGrid) {
				field = column.getTreeField();
			} else {
				field = column.getField();
			}
			sb.append("{field:\'" + field + "\',title:\'" + column.getTitle() + "\'");
			// 隐藏字段
			if (column.isHidden()) {
				sb.append(",hidden:true");
			}
			if (column.getWidth() != null) {
				sb.append(",width:" + column.getWidth());
			}
			if (column.getAlign() != null) {
				sb.append(",align:\'" + column.getAlign() + "\'");
			}
			// 字段排序
			if ((column.isSortable()) && (field.indexOf("_") <= 0 && !StringUtils.equals(field, "opt")) && !treeGrid) {
				sb.append(",sortable:" + column.isSortable() + "");
			}
			if (column.getFormatter() != null) {
				sb.append(",formatter:function(value,rec,index){");
				sb.append(" return " + column.getFormatter() + "(value,rec,index);}");
			}
			if (column.getField().equals("opt")) {// 加入操作
				sb.append(",formatter:function(value,rec,index){");
				this.getOptUrl(sb);
				sb.append("}");
			} else if (column.getDateFormat() != null) {
				sb.append(",formatter:function(value,rec,index){");
				sb.append(" return new Date().format('" + column.getDateFormat() + "',value);}");
			} else if (column.getShowLen() != null) { // 设置了显示多少长度的
				sb.append(",formatter:function(value,rec,index){");
				sb.append(" if(value==undefined) {return ''} ");
				sb.append(" if(value.length<=");
				sb.append(column.getShowLen());
				sb.append(") {return value}");
				sb.append(" else{ return '<a title= '+value+'>'+ value.substring(0,");
				sb.append(column.getShowLen());
				sb.append(")+'...';}}");
			} else if (columnValueList.size() > 0 && !column.getField().equals("opt")) {// 值替換
				String testString = "";
				for (ColumnValue columnValue : columnValueList) {
					if (columnValue.getName().equals(column.getField())) {
						String[] value = columnValue.getValue().split(",");
						String[] text = columnValue.getText().split(",");
						sb.append(",formatter:function(value,rec,index){");
						sb.append("if(value==undefined) return '';");
						sb.append("var valArray = value.split(',');");
						sb.append("if(valArray.length > 1){");
						sb.append("var checkboxValue = '';");
						sb.append("for(var k=0; k<valArray.length; k++){");
						for (int j = 0; j < value.length; j++) {
							sb.append("if(valArray[k] == '" + value[j] + "'){ checkboxValue = checkboxValue + \'"
									+ text[j] + "\' + ',';}");
						}
						sb.append("}");
						sb.append("return checkboxValue.substring(0,checkboxValue.length-1);");
						sb.append("}");
						sb.append("else{");
						for (int j = 0; j < value.length; j++) {
							testString += "if(value=='" + value[j] + "'){return \'" + text[j] + "\';}";
						}
						sb.append(testString);
						sb.append("else{return value;}");
						sb.append("}");
						sb.append("}");
					}
				}
			}
			// 背景设置
			if (columnStyleList.size() > 0 && !column.getField().equals("opt")) {
				String testString = "";
				for (ColumnValue columnValue : columnStyleList) {
					if (columnValue.getName().equals(column.getField())) {
						String[] value = columnValue.getValue().split(",");
						String[] text = columnValue.getText().split(",");
						sb.append(",styler:function(value,rec,index){");
						if ((value.length == 0 || StringUtils.isEmpty(value[0])) && text.length == 1) {
							if (text[0].indexOf("(") > -1) {
								testString = " return \'" + text[0].replace("(", "(value,rec,index") + "\'";
							} else {
								testString = " return \'" + text[0] + "\'";
							}
						} else {
							for (int j = 0; j < value.length; j++) {
								testString += "if(value=='" + value[j] + "'){return \'" + text[j] + "\'}";
							}
						}
						sb.append(testString);
						sb.append("}");
					}
				}

			}
			sb.append("}");
			// 去除末尾,
			if (i < columnList.size()) {
				sb.append(",");
			}
		}
	}

	/**
	 * 设置分页条信息
	 * 
	 * @param sb
	 */
	protected void setPager(StringBuffer sb, String grid) {
		sb.append("$(\'#" + name + "\')." + grid + "(\'getPager\').pagination({");
		sb.append("beforePageText:\'\'," + "afterPageText:\'/{pages}\',");
		sb.append("displayMsg:\'{from}-{to}" + ",共" + "{total}" + "条" + "\',");
		sb.append("showPageList:true,");
		sb.append("showRefresh:true,");
		sb.append("onBeforeRefresh:function(pageNumber, pageSize){ $(this).pagination(\'loading\'); }");
		sb.append("});");
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setIdField(String idField) {
		this.idField = idField;
	}

	public void setTreeGrid(boolean treeGrid) {
		this.treeGrid = treeGrid;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	public void setWidth(String width) {
		this.width = width;
	}

	public void setHeight(String height) {
		this.height = height;
	}

	public void setCheckbox(boolean checkbox) {
		this.checkbox = checkbox;
	}

	public void setOpenFirstNode(boolean openFirstNode) {
		this.openFirstNode = openFirstNode;
	}

	public void setFitColumns(boolean fitColumns) {
		this.fitColumns = fitColumns;
	}

	public void setSortName(String sortName) {
		this.sortName = sortName;
	}

	public void setSortOrder(String sortOrder) {
		this.sortOrder = sortOrder;
	}

	public void setOnLoadSuccess(String onLoadSuccess) {
		this.onLoadSuccess = onLoadSuccess;
	}

	public void setOnClick(String onClick) {
		this.onClick = onClick;
	}

	public void setOnDblClick(String onDblClick) {
		this.onDblClick = onDblClick;
	}

	public void setSingleSelect(Boolean singleSelect) {
		this.singleSelect = singleSelect;
	}

	public void setOptList(List<GridOpt> optList) {
		this.optList = optList;
	}

}
